<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>curl 转 Java HTTP 代码生成器</title>
    <style>
        :root {
            --primary: #4361ee;
            --primary-hover: #3a56d4;
            --text: #333;
            --text-light: #666;
            --bg: #f8f9fa;
            --bg-card: #ffffff;
            --border: #dee2e6;
            --radius: 10px;
            --shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
            --font: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }

        * {
            box-sizing: border-box;
        }

        body {
            font-family: var(--font);
            background-color: var(--bg);
            color: var(--text);
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        header {
            background: var(--primary);
            color: white;
            padding: 1rem 2rem;
            text-align: center;
        }

        header h1 {
            margin: 0;
            font-size: 1.4rem;
            font-weight: 600;
        }

        header p {
            margin: 0.3rem 0 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }

        .main-container {
            display: flex;
            flex: 1;
        }

        .panel {
            padding: 1.6rem;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .panel-left {
            flex: 1;
            background: var(--bg-card);
            border-right: 1px solid var(--border);
        }

        .panel-right {
            flex: 1.3; /* 右边更宽，适合代码 */
            background: var(--bg-card);
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text);
            font-weight: 500;
            font-size: 0.95rem;
        }

        textarea {
            width: 100%;
            min-height: 300px;
            padding: 12px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            font-family: 'Courier New', monospace;
            font-size: 0.95rem;
            resize: vertical;
            transition: border 0.3s ease;
        }

        textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.15);
        }

        button {
            padding: 10px 16px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: var(--radius);
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            margin-bottom: 1rem;
            align-self: flex-start;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: var(--primary-hover);
        }

        .copy-btn {
            background-color: #2dce89;
            margin-top: 0.5rem;
            padding: 8px 14px;
            font-size: 0.95rem;
        }

        .copy-btn:hover {
            background-color: #26af75;
        }

        .note {
            margin-top: 1.5rem;
            padding-top: 1rem;
            border-top: 1px dashed var(--border);
            color: var(--text-light);
            font-size: 0.85rem;
        }

        .note ul {
            margin: 0.5rem 0 0 1.2rem;
            padding: 0;
        }

        .note a {
            color: var(--primary);
            text-decoration: none;
        }

        .note a:hover {
            text-decoration: underline;
        }

        @media (max-width: 768px) {
            .main-container {
                flex-direction: column;
            }
            .panel-left, .panel-right {
                flex: auto;
            }
        }
    </style>
</head>
<body>

<header>
    <h1>🔧 curl 转 Java HTTP 代码生成器</h1>
    <p>左右布局 | 更宽代码区 | 一键复制 | 纯前端解析</p>
</header>

<div class="main-container">
    <!-- 左侧面板：输入 curl -->
    <div class="panel panel-left">
        <label for="curlInput">📌 粘贴 curl 命令：</label>
        <textarea id="curlInput" placeholder="curl -X POST 'https://example.com/api' \
-H 'Authorization: Bearer xxx' \
-H 'Content-Type: application/json' \
-d '{&#34;name&#34;:&#34;test&#34;}'
（支持换行和单引号）"></textarea>
        <button onclick="convertCurlToJava()">🚀 生成 Java 代码</button>

        <div class="note">
            <strong>📌 提示：</strong>
            <ul>
                <li>支持 <code>-X</code>, <code>-H</code>, <code>-d</code>, URL 自动识别</li>
                <li>使用 <a href="https://hutool.cn/" target="_blank">Hutool</a> 实现</li>
            </ul>
        </div>
    </div>

    <!-- 右侧面板：输出 Java 代码 -->
    <div class="panel panel-right">
        <label for="javaCode">✅ 生成的 Java 代码：</label>
        <textarea id="javaCode" readonly></textarea>
        <button class="copy-btn" onclick="copyToClipboard()">📋 复制到剪贴板</button>
    </div>
</div>

<script>
function convertCurlToJava() {
    const curlStr = document.getElementById('curlInput').value.trim();
    if (!curlStr) {
        alert("请输入 curl 命令！");
        return;
    }

    try {
        let cmd = curlStr.trim().replace(/^curl\s+/i, '');

        const result = {
            method: 'GET',
            url: '',
            headers: {},
            data: null
        };

        const methodMatch = cmd.match(/-X\s+([A-Z]+)/i);
        if (methodMatch) {
            result.method = methodMatch[1].toUpperCase();
            cmd = cmd.replace(methodMatch[0], '');
        }

        const headerMatches = [...cmd.matchAll(/-H\s+'([^']+)'/gi)];
        headerMatches.forEach(match => {
            const header = match[1];
            const sep = header.indexOf(':');
            if (sep > 0) {
                const key = header.substring(0, sep).trim();
                const value = header.substring(sep + 1).trim();
                result.headers[key] = value;
            }
            cmd = cmd.replace(match[0], '');
        });

        const dataMatch = cmd.match(/-d\s+'((?:[^'\\]|\\.)*)'/s);
        if (dataMatch) {
            result.data = dataMatch[1]
                .replace(/\\'/g, "'")
                .replace(/\\"/g, '"')
                .replace(/\\\\/g, '\\');
            cmd = cmd.replace(dataMatch[0], '');
        }

        const urlMatch = cmd.match(/'(https?:\/\/[^']+)'/) ||
                         cmd.match(/"(https?:\/\/[^"]+)"/) ||
                         cmd.match(/\s(https?:\/\/[^\s]+)/);
        if (urlMatch) {
            result.url = urlMatch[1];
        } else {
            throw new Error("未找到有效的 URL");
        }

        // 生成 Java 代码
        let javaCode = `import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

/**
 * 自动生成：curl 转 Java 请求
 */
public class CurlToJava {
    public static void main(String[] args) {
        String url = "${result.url.replace(/"/g, '\\"')}";
        String requestBody = ${result.data ? JSON.stringify(result.data) : "null"};

        HttpResponse response = null;
        try {
            response = HttpRequest.${result.method.toLowerCase()}(url)`;

        Object.keys(result.headers).forEach(key => {
            const value = result.headers[key].replace(/"/g, '\\"');
            javaCode += `
                    .header("${key}", "${value}")`;
        });

        if (result.data && ['POST', 'PUT', 'PATCH'].includes(result.method)) {
            javaCode += `
                    .body(requestBody)`;
        }

        javaCode += `
                    .timeout(10000)
                    .execute();

            System.out.println("响应: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) response.close();
        }
    }
}`;

        document.getElementById('javaCode').value = javaCode;

    } catch (error) {
        document.getElementById('javaCode').value = `// ❌ 解析失败：${error.message}`;
    }
}

function copyToClipboard() {
    const textarea = document.getElementById('javaCode');
    textarea.select();
    document.execCommand('copy');
    alert('✅ 代码已复制到剪贴板！');
}
</script>

</body>
</html>